package AddonTemp;

use strict;
use warnings;

use File::Spec;
use File::Temp;
use File::Path;
use IO::Dir;

BEGIN {
    use Exporter ();
    our ( $VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS );

    $VERSION = sprintf( "%d", q$Revision$ =~ m{\d+} );
    @ISA     = qw(Exporter);
    @EXPORT  = qw(&get_temp_tree
        &clean_temp_trees
        &get_temp_path);
    %EXPORT_TAGS = ();
    @EXPORT_OK   = qw();
} ## end BEGIN

sub get_temp_tree(;$ );
sub clean_temp_trees( );
sub get_temp_path($ );

sub get_temp_tree(;$ ) {
    my ( $pid ) = shift;
    $pid = $$ unless defined $pid;
    return File::Spec->catdir( File::Spec->tmpdir, "addonpkg." . $pid );
}

sub clean_temp_trees( ) {

    # Remove temporary directories that might have been left from other processes
    my %pids = ();
    my $dirh = new IO::Dir( File::Spec->tmpdir );
    return unless $dirh;
    foreach ( $dirh->read ) {
        $pids{ $1 } = 1 if m{^addonpkg\.(\d+)$};
    }
    $dirh->close;
    undef $dirh;
    foreach my $pid ( keys %pids ) {
        unless ( kill 0, $pid ) {
            my $path = get_temp_tree( $pid );
            rmtree( $path );
        }
    } ## end foreach my $pid ( keys %pids)
} ## end sub clean_temp_trees( )
clean_temp_trees;

END {
    my $self_path = get_temp_tree;
    if ( -d $self_path ) {
        rmtree( $self_path );
    }
} ## end END

sub get_temp_path($ ) {
    my $base = get_temp_tree;
    mkpath( $base, 0, 0777 ) unless -d $base;
    my $randomdir = File::Temp::tempdir( DIR => $base );
    my $path = File::Spec->catdir( $randomdir, shift );
    mkpath( $path, 0, 0777 );
    return $path;
} ## end sub get_temp_path($ )

1;
